package com.sys.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.sys.platform.common.utils.HttpUtils;
import com.sys.platform.entity.NoticeLog;
import com.sys.platform.entity.request.Notice.NoticeLogVO;
import com.sys.platform.entity.request.Notice.NoticeRequestDTO;
import com.sys.platform.entity.request.Notice.NoticeSearchDTO;
import com.sys.platform.entity.request.Notice.NoticeVO;
import com.sys.platform.mapper.NoticeLogMapper;
import com.sys.platform.service.IVoiceNoticeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class VoiceNoticeServiceImpl implements IVoiceNoticeService {

    @Resource
    private NoticeLogMapper noticeLogMapper;

    public void sendSmsOrCallNotice(NoticeRequestDTO noticeRequestDTO) {
        String httpUrl = "http://10.36.1.188/cgi-bin/NoticePush";
        HttpPost httpPost = new HttpPost(httpUrl);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        Map requestData = new HashMap<>();
        requestData.put("Type", noticeRequestDTO.getNoticeType());
        requestData.put("To", noticeRequestDTO.getPhoneNumber());
        requestData.put("Text", noticeRequestDTO.getNoticeContent());
        requestData.put("Encoding", "UTF-8");
        log.info("voice notice request:{}", requestData);
        StringEntity entity = new StringEntity(JSONObject.toJSONString(requestData), "UTF-8");
        httpPost.setEntity(entity);
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        try {
            HttpResponse response = closeableHttpClient.execute(httpPost);
            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(jsonStr);

            for (String phone : noticeRequestDTO.getPhoneNumber()) {
                NoticeLog noticeLog = new NoticeLog();
                noticeLog.setTo(phone);
                noticeLog.setNotice(noticeRequestDTO.getNoticeContent());
                noticeLog.setMethod(NoticeRequestDTO.NoticeTypeEnum.valueOf(noticeRequestDTO.getNoticeType()).getDescription());
                noticeLog.setNoticeTime(DateTime.now());
                noticeLogMapper.insertSelective(noticeLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        executorService.schedule(() -> sendingRecords(), 1L, TimeUnit.MINUTES);
    }

    public List<NoticeLogVO> getNoticeLogList(NoticeSearchDTO dto) {
        NoticeLog noticeLog = new NoticeLog();
        BeanUtil.copyProperties(dto, noticeLog, CopyOptions.create().ignoreNullValue());
        List<NoticeLog> noticeLogs = noticeLogMapper.selectNoticeLogList(noticeLog);
        if (CollectionUtils.isEmpty(noticeLogs)) {
            return new ArrayList<>();
        }
        return noticeLogs.stream().map(item -> {
            NoticeLogVO vo = new NoticeLogVO();
            BeanUtil.copyProperties(item, vo, CopyOptions.create().ignoreNullValue());
            return vo;
        }).collect(Collectors.toList());
    }

    public void sendingRecords() {
        try {
            String response = HttpUtils.getRequest("http://10.36.1.188/cgi-bin/NoticeResult", String.class);
            List<NoticeVO> noticeVOS = JSONObject.parseArray(response, NoticeVO.class);
            if (CollectionUtils.isEmpty(noticeVOS)) {
                return;
            }
            for (NoticeVO noticeVO : noticeVOS) {
                NoticeLog noticeLog = new NoticeLog();
                BeanUtil.copyProperties(noticeVO, noticeLog, CopyOptions.create().ignoreNullValue());
                noticeLog.setSendTime(noticeVO.getTime());
                noticeLogMapper.updateByPrimaryKeySelective(noticeLog);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
